package cn.finyzq.ss.games.web.interceptor;

import cn.finyzq.ss.games.utils.HttpUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import java.util.Map;

/**
 * Create Time: 2018年08月05日 14:55
 *
 * @author fin
 */
public class WebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    /** logger */
    private Logger logger = LogManager.getLogger(WebSocketInterceptor.class);


    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {

        //解决The extension [x-webkit-deflate-frame] is not supported问题
        if (request.getHeaders().containsKey("Sec-WebSocket-Extensions")) {
            request.getHeaders().set("Sec-WebSocket-Extensions", "permessage-deflate");
        }
        attributes.putAll(HttpUtils.getRequestParameterSingleMap(((ServletServerHttpRequest) request).getServletRequest()));
//        attributes.put("user", SessionUtils.getUser(((ServletServerHttpRequest) request).getServletRequest()));
//        attributes.put("response", ((ServletServerHttpResponse) response).getServletResponse());
        logger.info("Websocket before handshake");
        return super.beforeHandshake(request, response, wsHandler, attributes);
    }

    @Override
    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception ex) {

        if(request.getHeaders().containsKey("Sec-WebSocket-Protocol")){
            response.getHeaders().set("Sec-WebSocket-Protocol", String.valueOf(request.getHeaders().get("Sec-WebSocket-Protocol")));
        }
        logger.info("After Handshake");
        super.afterHandshake(request, response, wsHandler, ex);
    }
}